/**
 * Generali Solutions d'assurances - Tous droits réservés &copy; 2007 - 2010
 */

package fr.generali.accueilclient.utils.spel.mapping.support;

import org.springframework.beans.BeanUtils;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;

import fr.generali.accueilclient.utils.spel.mapping.support.MapperFactory;

/**
 * @author Holmes Kelly
 */
public class MappingConversionService implements ConversionService {

    /**
     * 
     */
    private ConversionService delegate;

    /**
     * @param delegate conversion service
     */
    public MappingConversionService(ConversionService delegate) {
        this.delegate = delegate;
    }

    /**
     * {@inheritDoc}
     */
    public boolean canConvert(Class< ? > sourceType, Class< ? > targetType) {
        return this.delegate.canConvert(sourceType, targetType);
    }

    /**
     * {@inheritDoc}
     */
    public boolean canConvert(TypeDescriptor sourceType, TypeDescriptor targetType) {
        return this.delegate.canConvert(sourceType, targetType);
    }

    /**
     * {@inheritDoc}
     */
    public <T> T convert(Object source, Class<T> targetType) {
        if (source == null || this.delegate.canConvert(source.getClass(), targetType)) {
            return this.delegate.convert(source, targetType);
        } else {
            return (T ) MapperFactory.defaultMapper().map(source, BeanUtils.instantiate(targetType));
        }
    }

    /**
     * {@inheritDoc}
     */
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        return null;
    }

}
